//
//  zhexianTuView.m
//  sellHouse
//
//  Created by 李 佳伟 on 2018/11/21.
//  Copyright © 2018年 李 佳伟. All rights reserved.
//

#import "zhexianTuView.h"
#import "JTCSM.h"
static CGFloat bounceX = 40;
static CGFloat bounceY = 20;

static CGFloat numberX = 7;
static NSInteger Ydivision= 4;



@interface zhexianTuView ()<CAAnimationDelegate>
{
    NSInteger countq;
    NSInteger numberY;
    
}

@property (nonatomic,strong) NSMutableArray *mylist;
@property (nonatomic, strong)UIBezierPath * path1;

/** 背景视图 */
@property (nonatomic, strong) UIView *gradientBackgroundView;
/** 渐变图层 */
@property (nonatomic, strong) CAGradientLayer *gradientLayer;
/** 颜色数组 */
@property (nonatomic, strong) NSMutableArray *gradientLayerColors;



@end

@implementation zhexianTuView

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.

*/

- (void)drawRect:(CGRect)rect {
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(context, 2.0);
    CGContextSetRGBStrokeColor(context, 1, 0, 0, 0);
    CGContextMoveToPoint(context, bounceX, bounceY);
    CGContextAddLineToPoint(context, bounceX, rect.size.height - bounceY);
    CGContextStrokePath(context);
}

#pragma mark 创建x轴的数据
- (void)createLabelX{
    CGFloat  month = self.mylist.count;
    CGFloat labelWidth = (self.frame.size.width - 2*bounceX)/(month-1)-3;
    for (NSInteger i = 0; i < month; i++) {
        NSDictionary *dict = [self.mylist objectAtIndex:i];
        UILabel * LabelMonth = [[UILabel alloc]initWithFrame:CGRectMake(labelWidth * i + bounceX, self.frame.size.height - bounceY + bounceY*0.3,labelWidth , bounceY/2)];
        LabelMonth.tag = 1000 + i;
        LabelMonth.text = [NSString stringWithFormat:@"%@日",[dict objectForKey:@"day"]];
        LabelMonth.font = [UIFont systemFontOfSize:10];
        [self addSubview:LabelMonth];
        LabelMonth.userInteractionEnabled = YES;
        [self setlongTapWithView:LabelMonth];
    }
    
}
#pragma mark 创建y轴数据
- (void)createLabelY{
    
    while (numberY%3!=0) {
        numberY++;
    }
    NSLog(@"--%ld",(long)numberY);
    
    for (NSInteger i = 0; i < Ydivision; i++) {
        UILabel * labelYdivision = [[UILabel alloc]initWithFrame:CGRectMake(0, (self.frame.size.height -  2*bounceY)/(Ydivision-1) *i + bounceY-bounceY/2, bounceX, bounceY)];
        labelYdivision.tag = 2000 + i;
        labelYdivision.text = [NSString stringWithFormat:@"%ld",(3 - i)*(numberY/3)];
        labelYdivision.font = [UIFont systemFontOfSize:10];
        labelYdivision.textAlignment = NSTextAlignmentCenter;
        [self addSubview:labelYdivision];
    }
}
- (void)drawGradientBackgroundView {
    // 渐变背景视图（不包含坐标轴）
    self.gradientBackgroundView = [[UIView alloc] initWithFrame:CGRectMake(bounceX, bounceY, self.bounds.size.width - bounceX*2, self.bounds.size.height - 2*bounceY)];
    [self addSubview:self.gradientBackgroundView];
    /** 创建并设置渐变背景图层 */
    //初始化CAGradientlayer对象，使它的大小为渐变背景视图的大小
    self.gradientLayer = [CAGradientLayer layer];
    self.gradientLayer.frame = self.gradientBackgroundView.bounds;
    //设置渐变区域的起始和终止位置（范围为0-1），即渐变路径
    self.gradientLayer.startPoint = CGPointMake(0, 0.0);
    self.gradientLayer.endPoint = CGPointMake(1.0, 0.0);
    //设置颜色的渐变过程
    self.gradientLayerColors = [NSMutableArray arrayWithArray:@[(__bridge id)[UIColor whiteColor].CGColor, (__bridge id)[UIColor whiteColor].CGColor]];
    self.gradientLayer.colors = self.gradientLayerColors;
    //将CAGradientlayer对象添加在我们要设置背景色的视图的layer层
    [self.gradientBackgroundView.layer addSublayer:self.gradientLayer];
    self.gradientBackgroundView.backgroundColor=[UIColor clearColor];
    [self addSubview:self.gradientBackgroundView];
    
    //[self.layer addSublayer:self.gradientLayer];
}

#pragma mark 添加虚线
- (void)setLineDash{
    
    for (NSInteger i = 0;i < Ydivision; i++ ) {
        CAShapeLayer * dashLayer = [CAShapeLayer layer];
        dashLayer.strokeColor = [UIColor colorWithRed:241/255.0 green:241/255.0 blue:241/255.0 alpha:241/255.0].CGColor;
        dashLayer.fillColor = [[UIColor colorWithRed:241/255.0 green:241/255.0 blue:241/255.0 alpha:241/255.0] CGColor];
        // 默认设置路径宽度为0，使其在起始状态下不显示
        dashLayer.lineWidth = 0.5;
        UILabel * label1 = (UILabel*)[self viewWithTag:2000 + i];//获取x轴数据label的位置根据其位置画横虚线
        
        UIBezierPath * path = [[UIBezierPath alloc]init];
        path.lineWidth = 0.5;
        UIColor * color = [UIColor blueColor];
        
        [color set];
        [path moveToPoint:CGPointMake( 0, label1.frame.origin.y - bounceY/2)];
        [path addLineToPoint:CGPointMake(self.frame.size.width - 2*bounceX,label1.frame.origin.y - bounceY/2)];
        CGFloat dash[] = {10,10};
        [path setLineDash:dash count:2 phase:10];
        [path stroke];
        dashLayer.path = path.CGPath;
        [self.gradientBackgroundView.layer addSublayer:dashLayer];
    }
}

#pragma mark 画折线
- (void)dravLineWithType:(LINETYPE)type datasource:(NSMutableArray *)list{
    
    UIColor *linecolor = type==DAIKAN_TYPE?RGBACOLOR(15,166,232, 1):(type==SHOCANG_TYPE?RGBACOLOR(225, 135, 38, 1):RGBACOLOR(241, 124, 202, 1));
    NSInteger tag = (type ==DAIKAN_TYPE)?3000:(type==SHOCANG_TYPE)?4000:5000;
    CAShapeLayer *lineChartLayer;
    UILabel * label = (UILabel*)[self viewWithTag:1000];//根据横坐标上面的label 获取直线关键点的x 值
    UIBezierPath * path = [[UIBezierPath alloc]init];
    path.lineWidth = 0.3;
    self.path1 = path;
    UIColor * color = [UIColor greenColor];
    [color set];
    [path moveToPoint:CGPointMake( label.frame.origin.x - bounceX, (self.frame.size.height - bounceY*2 ))];
    
    
//    //创建折现点标记
    NSInteger MaxNum = numberY;
    CGFloat maxnumber_float = numberY;
    if (MaxNum == 0) {
        return;
    }
    for (NSInteger i = 1; i< numberX; i++) {
        NSDictionary *dict = list[i-1];
        NSInteger  arc = [[dict objectForKey:@"count"] integerValue];
        UILabel * label1 = (UILabel*)[self viewWithTag:1000 + i];
        [path addLineToPoint:CGPointMake(label1.frame.origin.x - bounceX+5,  (MaxNum -arc) /maxnumber_float * (self.frame.size.height - bounceY*2 ) )];
        UILabel * falglabel;
        if([self viewWithTag:tag+i] ==nil){
            falglabel = [[UILabel alloc]init];
        }
        falglabel.frame=CGRectMake(label1.frame.origin.x , (MaxNum -arc) /maxnumber_float * (self.frame.size.height - bounceY*2 ), 30, 15);
        //  falglabel.backgroundColor = [UIColor blueColor];
        falglabel.tag = tag+i;
        falglabel.hidden = YES;
        falglabel.textColor = linecolor;
        falglabel.text = [NSString stringWithFormat:@"%ld",arc];
        falglabel.font = [UIFont systemFontOfSize:8.0];
        [self addSubview:falglabel];
    }
     [path stroke];
 
    
    
   lineChartLayer = [CAShapeLayer layer];
    lineChartLayer.path = path.CGPath;
    lineChartLayer.strokeColor = linecolor.CGColor;
    lineChartLayer.fillColor = [[UIColor clearColor] CGColor];
//    径宽度为0，使其在起始状态下不显示
    lineChartLayer.lineWidth = 0;
    lineChartLayer.lineCap = kCALineCapRound;
    lineChartLayer.lineJoin = kCALineJoinRound;
    
    [self.gradientBackgroundView.layer addSublayer:lineChartLayer];//直接添加导视图上
//    self.gradientBackgroundView.layer.mask = self.lineChartLayer;
    [self setanimationWithShapeLayer:lineChartLayer];
    
   (type ==DAIKAN_TYPE)?(self.daikanlineChartLayer =lineChartLayer):(type==SHOCANG_TYPE)?(self.shoucanglineChartLayer =lineChartLayer):(self.touchlineChartLayer =lineChartLayer);
    
}


- (instancetype)initWithFrame:(CGRect)frame withDatalist:(HouseZhexianModel *)list{
    
 if (self = [super initWithFrame:frame]) {
     self.backgroundColor = [UIColor whiteColor];
     self.userInteractionEnabled= YES;
     countq=0;
     if (list != nil) {
         self.mylist = list.takeCount.mutableCopy;
         NSInteger click = [self getMaxNumberL:list.clickCount];
         NSInteger collect = [self getMaxNumberL:list.collectCount];
         NSInteger take = [self getMaxNumberL:list.takeCount];
         numberY = (click>=collect?click:(collect>=take?collect:take));

         self.daikan_show=YES;
         self.shoucang_show = YES;
         self.touch_show = YES;
         [self createLabelX];
         [self createLabelY];
         [self drawGradientBackgroundView];
         [self setLineDash];
     }
     
     
     
 }
 return self;
}

#pragma mark 获取最大数
- (NSInteger)getMaxNumberL:(NSArray *)list{
    NSMutableArray *price = [NSMutableArray array];
    for (NSDictionary *item in list) {
        [price addObject: [NSNumber numberWithInteger:[item[@"count"] integerValue]]];
    }
    NSInteger maxPrice = [[price valueForKeyPath:@"@max.integerValue"] integerValue];
    
    return maxPrice;
}

#pragma mark 动画
- (void)setanimationWithShapeLayer:(CAShapeLayer*)layer{

        layer.lineWidth = 1;
        CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@"strokeEnd"];
        pathAnimation.duration = 3;
        pathAnimation.repeatCount = 1;
        pathAnimation.removedOnCompletion = YES;
        pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
        pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
        // 设置动画代理，动画结束时添加一个标签，显示折线终点的信息
        pathAnimation.delegate = self;
        [layer addAnimation:pathAnimation forKey:@"strokeEnd"];
        [self setNeedsDisplay];

}

- (void)setlongTapWithView:(UILabel *)label{
       UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
        longPressGesture.minimumPressDuration=1.5f;//设置长按 时间
        [label addGestureRecognizer:longPressGesture];
}

-(void)longPress:(UILongPressGestureRecognizer*)gusture{
    UILabel *label = (UILabel *)[gusture view];
    NSInteger index = label.tag-1000;
    
    UILabel *show1label = [self viewWithTag:3000+index];
    UILabel *show2label = [self viewWithTag:4000+index];
    UILabel *show3label = [self viewWithTag:5000+index];
    
  if(gusture.state==UIGestureRecognizerStateBegan){
     NSLog(@"startPress");
      if (self.daikan_show) {
           show1label.hidden = NO;
          NSLog(@"startPress1");
      }
      if (self.shoucang_show) {
          show2label.hidden = NO;
          NSLog(@"startPress2");
      }
      if (self.touch_show) {
          show3label.hidden = NO;
          NSLog(@"startPress3");
      }
     
  }else if(gusture.state==UIGestureRecognizerStateEnded){
    NSLog(@"endPress");
      show1label.hidden= YES;
      show2label.hidden= YES;
      show3label.hidden= YES;
  }
   
}

@end
